package com.summer.controller.thirdpart;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.summer.controller.BaseController;
import com.summer.entity.UserInfo;
import com.summer.mapper.UserInfoMapper;
import com.summer.service.thirdpart.IHuLuService;
import com.summer.util.CallBackResult;
import com.summer.util.Constant;
import com.summer.util.ConverterUtils;
import com.summer.util.ServiceResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户运营商认证
 * 
 * @author 2016年12月9日 16:51:09
 * @param
 */
@Slf4j
@RestController
@RequestMapping("/v1.0/api/web")
public class HuLuController extends BaseController {

	@Resource
	private IHuLuService huLuService;
	@Resource
	private UserInfoMapper userInfoMapper;


	
	/**
	 * 申请认证令牌接口
	 * 
	 * @return
	 */
	@PostMapping("/getToken")
	public String verificationHL(@RequestBody String jsonData,HttpServletRequest request) {
		Map<String, Object> param = JSONObject.parseObject(jsonData);
		log.info("HuLuController getToken param=" + param.toString());
		String recode = ConverterUtils.toString(param.get("recode"));
		String clientType = ConverterUtils.toString(param.get("clientType"));
		String deviceId = ConverterUtils.toString(param.get("deviceId"));
		String mobilePhone = ConverterUtils.toString(param.get("mobilePhone"));
		HashMap<String, Object> params = new HashMap<String, Object>();
		String token = null;
		String website = null;
		String phone = null;
		UserInfo user = getLoginUser(request,mobilePhone);
		if(!Constant.TYPE_CLIENT_IOS.equals(clientType)){
			clientType = Constant.TYPE_CLIENT_ANDROID;
		}
		Map<String,Object> res = new HashMap<String,Object>(){{
			put("recode", recode);
			put("deviceId", deviceId);
			put("mobilePhone", mobilePhone);
		}};
		res.put("clientType", clientType);
		String msg ="成功";
		Integer code = CallBackResult.SUCCESS;

		try {
			if(user==null){
				return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "请重新登录",res);
			}
			if(Constant.USER_AUTHENTIC==user.getMobileAuthentic()){
				return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "用户已认证",res);
			}
			phone = user.getPhone();

			String userFcName = user.getFirstContactName();// 第一联系人姓名
			String userFcPhone = user.getFirstContactPhone();// 第一联系人电话
			String userFcRelation = user.getFirstContactRelation().toString();// 第一联系人关系
			String userScName = user.getSecondContactName();// 第二联系人关系
			String userScPhone = user.getSecondContactPhone();// 第二联系人关系
			String userScRelation = user.getSecondContactRelation().toString();// 第二联系人关系
			if (StringUtils.isNotBlank(userFcRelation)) {
				if ("1".equals(userFcRelation) || "2".equals(userFcRelation)) {// 父母
					userFcRelation = "PARENT";
				} else if ("3".equals(userFcRelation)
						|| "4".equals(userFcRelation)) {// 子女
					userFcRelation = "CHILD";
				} else if ("5".equals(userFcRelation)) {// 配偶
					userFcRelation = "COUPLE";
				}
				else{  //朋友
					userFcRelation = "FRIEND";
				}
			}
			if (StringUtils.isNotBlank(userScRelation)) {
				if ("1".equals(userScRelation)) {// 同学
					userScRelation = "CLASSMATE";
				} else if ("2".equals(userScRelation)) {// 亲戚
					userScRelation = "SIBBING";
				} else if ("3".equals(userScRelation)) {// 同事
					userScRelation = "COLLEAGUE";
				}else{      //朋友
					userScRelation = "FRIEND";
				}
			}
			String contacts = "";
			String contacts2 = "";
			if (StringUtils.isNotBlank(userFcName) && StringUtils.isNotBlank(userFcPhone)
					&& StringUtils.isNotBlank(userFcRelation)) {
				contacts = "{contact_tel:\"" + userFcPhone
						+ "\",contact_name:\"" + userFcName
						+ "\",contact_type:\"" + userFcRelation + "\"}";
			}
			if (StringUtils.isNotBlank(userScName)&& StringUtils.isNotBlank(userScPhone)
					&& StringUtils.isNotBlank(userScRelation)) {
				contacts2 = ",{contact_tel:\"" + userScPhone
						+ "\",contact_name:\"" + userScName
						+ "\",contact_type:\"" + userScRelation + "\"}";
			}
			params.put("userName", user.getRealName());
			params.put("cardNum", user.getIdCard());
			params.put("userPhone", phone);
			params.put("userId", user.getId());
			params.put("contacts", contacts + contacts2);
			params.put("first_contact_name",userFcName );
			params.put("first_contact_type", userFcRelation);
			params.put("first_contact_cell_phone_number", userFcPhone);
			params.put("second_contact_name", userScName);
			params.put("second_contact_type", userScRelation);
			params.put("second_contact_cell_phone_number", userScPhone);

			ServiceResult serviceResult = huLuService.getToken(params);

			if (serviceResult.isSuccessed()) {
				token = serviceResult.getMsg();
				website = serviceResult.getExt().toString();
			} else {
				code = CallBackResult.BUSINESS_ERROR;
				msg = serviceResult.getMsg();
			}

		} catch (Exception e) {
			log.error("hl getToken error phone="+phone, e);
			code = 500;
			msg = "系统异常";
		} finally {
			if ("300".equals(recode)) {
				msg = "密码错误";
			} else if ("400".equals(recode)) {
				msg = "请填写有效数据";
			} else if ("500".equals(recode)) {
				msg = "重新发起认证流程";
			}
		}
		res.put("token", token);
		res.put("website", website);
		res.put("userPhone", phone);
		return CallBackResult.returnJson(code, msg,res);
	}
	
	
	
	/**
	 * 提交登录接口
	 * 
	 * @return
	 */
	@PostMapping("/checkPassword")
	public String checkPassword(@RequestBody String jsonData,HttpServletRequest request) {
		Map<String, Object> param = JSONObject.parseObject(jsonData);
		log.info("HuLuController checkPassword param=" + param.toString());
		String mobilePhone = ConverterUtils.toString(param.get("mobilePhone"));
		UserInfo user = getLoginUser(request,mobilePhone);
		Map<String,Object> res = new HashMap<>();
		if(user==null){
			return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "请重新登录",res);
		}
		Integer code = 500;
		String msg = "查询失败！";
		String token = ConverterUtils.toString(param.get("token"));
		String website = ConverterUtils.toString(param.get("website"));
		String password = ConverterUtils.toString(param.get("password"));
		String queryPwd = ConverterUtils.toString(param.get("queryPwd"));
		String deviceId = ConverterUtils.toString(param.get("deviceId"));
		String clientType = ConverterUtils.toString(param.get("clientType"));

		ServiceResult serviceResults = new ServiceResult("500", "未知异常，请稍后重试！");
		HashMap<String, Object> params = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(website)&& StringUtils.isNotBlank(token)&&StringUtils.isNotBlank(password)) {
			params.put("userPhone", user.getPhone());
			params.put("userId", user.getId());
			params.put("website", website);
			params.put("password", password);
			params.put("token", token);
			if (StringUtils.isNotBlank(queryPwd)) {
				params.put("queryPwd", queryPwd);
			}
			params.put("CAPTCHA", "");
			serviceResults = huLuService.getCaptcha(params);// 获得验证码请求

			res.put("clientType", clientType);
			if ("100".equals(serviceResults.getCode())) {// code为100时。用户不需要输入密码。直接认证成功。
				code = 200;
				msg = "提交成功！并开始采集数据";
				res.put("deviceId", deviceId);
				res.put("clientType", clientType);
				return CallBackResult.returnJson(code, msg,res);
			} else if ("200".equals(serviceResults.getCode())) {// 发送验证码
				code = 200;
				msg = "验证码发送成功！";
			} else if ("400".equals(serviceResults.getCode())) {
				code = 400;
				msg = "重新发起流程，请输入有效数据！";
				res.put("recode", code);
				res.put("deviceId", deviceId);
				return CallBackResult.returnJson(code, msg,res);
			} else if ("500".equals(serviceResults.getCode())) {
				code = 500;
				msg = "请求失败，请重新发起流程！";
				res.put("recode", code);
				res.put("deviceId", deviceId);
				return CallBackResult.returnJson(code, msg,res);
			} else {// 请求成功，返回失败信息
				msg = serviceResults.getMsg();
				res.put("deviceId", deviceId);
				res.put("mobilePhone", mobilePhone);
				return CallBackResult.returnJson(code, msg,res);
			}

		} else {
			code = 500;
			msg = "请输入有效数据！";
			res.put("deviceId", deviceId);
			return CallBackResult.returnJson(code, msg,res);
		}
		res.put("deviceId", deviceId);
		res.put("queryPwd", queryPwd);
		res.put("token", token);
		res.put("website", website);
		res.put("password", password);
		res.put("mobilePhone", mobilePhone);
		res.put("userPhone", user.getPhone());
		return CallBackResult.returnJson(code, msg,res);

	}

	/**
	 * 提交短信验证码接口
	 * @param request
	 * @return
	 */
	@PostMapping("/checkCaptcha")
	public String checkCaptcha(@RequestBody String jsonData,HttpServletRequest request) {
		Map<String, Object> param = JSONObject.parseObject(jsonData);
		log.info("HuLuController checkCaptcha param=" + param.toString());
		String mobilePhone = ConverterUtils.toString(param.get("mobilePhone"));
		UserInfo user = getLoginUser(request,mobilePhone);
		Map<String,Object> res = new HashMap<>();


		Integer code = 500;
		String msg = "查询失败！";
		String token = ConverterUtils.toString(param.get("token"));
		String website = ConverterUtils.toString(param.get("website"));
		String password = ConverterUtils.toString(param.get("password"));
		String queryPwd = ConverterUtils.toString(param.get("queryPwd"));
		String deviceId = ConverterUtils.toString(param.get("deviceId"));
		String clientType = ConverterUtils.toString(param.get("clientType"));
		String needQueryPwd = ConverterUtils.toString(param.get("needQueryPwd"));
		String captcha = ConverterUtils.toString(param.get("SUBMIT_CAPTCHA"));

		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");

		HashMap<String, Object> params = new HashMap<String, Object>();
		res.put("deviceId", deviceId);
		res.put("mobilePhone", mobilePhone);
		res.put("clientType", clientType);
		if(user==null){
			return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "请重新登录",res);
		}
		if (StringUtils.isNotBlank(captcha) && StringUtils.isNotBlank(token)) {
			params.put("CAPTCHA", captcha);
			params.put("userPhone", user.getPhone());
			params.put("userId", user.getId());
			params.put("password", password);
			params.put("token", token);
			params.put("website", website);
			if ("need".equals(needQueryPwd)) {
				params.put("queryPwd", queryPwd);
			}
			ServiceResult serviceResults = new ServiceResult("500", "未知异常，请稍后重试！");
			serviceResults = huLuService.getCaptcha(params);//提交验证码请求
			if("100".equals(serviceResults.getCode())){
				code = 200;
				msg = "提交验证码成功！并开始采集数据";
				if (StringUtils.isNotBlank(token)) {
					if (user.getId() != null) {
						UserInfo newUser = new UserInfo();
						newUser.setId(user.getId());
						newUser.setMobileAuthentic(Constant.USER_AUTHENTIC);
						userInfoMapper.updateByPrimaryKeySelective(newUser);
					}
				}
				return CallBackResult.returnJson(code, msg,res);
			}else if("200".equals(serviceResults.getCode())){
				res.put("token", token);
				res.put("website", website);
				res.put("queryPwd", queryPwd);
				res.put("userId", user.getId());
				res.put("userPhone", user.getPhone());
				res.put("CAPTCHA", "");
				return CallBackResult.returnJson(code, msg,res);
			}else{
				code = 400;
				res.put("recode", code);
				return CallBackResult.returnJson(code, msg,res);
			}
		}
		res.put("token", token);
		res.put("deviceId", deviceId);
		res.put("mobilePhone", mobilePhone);
		return CallBackResult.returnJson(code, msg,res);
	}


	/**
	 * 查询手机号码归属地
	 * @param request
	 * @return
	 */
	@PostMapping("/findMobileBelong")
	public String findMobileBelong(@RequestBody String jsonData,HttpServletRequest request) {
		Map<String, Object> params = JSONObject.parseObject(jsonData);
		log.info("HuLuController findMobileBelong param=" + params.toString());
		String mobilePhone = ConverterUtils.toString(params.get("mobilePhone"));
		UserInfo user = getLoginUser(request,mobilePhone);
		Map<String,Object> res = new HashMap<>();

		Integer code = 500;
		String msg = "查询失败！";
		String phone = ConverterUtils.toString(params.get("phone"));
		String website = ConverterUtils.toString(params.get("website"));
		if(StringUtils.isBlank(phone)){
			phone = user.getPhone();
		}
		String idCard = user.getIdCard();
		String param = "phone="+phone+"&idNumber="+ idCard;
		HashMap<String, Object>  map = new HashMap<String, Object>();
		map.put("phone", phone);
		map.put("idNumber", idCard);
		map.put("website", website);
		CallBackResult mobileBelong = huLuService.findMobileBelong(map);
		return JSONObject.toJSONString(mobileBelong, SerializerFeature.WriteMapNullValue);
	}
}
